#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/1/16 17:18
# @Author  : cong
# @FileName: mp3.py
# @Software: PyCharm
import os
import time

import requests
import re


def download_mp3(link):
    heaers = {
        'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36'
    }
    while True:
        try:
            # print("请求：",link)
            html = requests.get(link, heaers)
            break
        except Exception  as e:
            print("异常：", e)
            time.sleep(10)
    html.encoding = html.apparent_encoding
    # print(html.text)
    pattern = r'<a\s+href="([^"]*)"\s+title="([^"]*)"'
    music_link = re.findall(pattern, html.text)
    for i in music_link:
        print(i)

    for index in music_link:
        url = 'http://www.36dj.com' + index[0]
        # print("请求：",url)
        title = index[1]
        mp3_name = title + ".mp3"
        while True:
            try:
                html_data = requests.get(url, heaers)
                break
            except Exception  as e:
                print("异常：", e)
                time.sleep(10)

        pattern1 = r'"playurl": "([^"]*)"'
        mp3_url = re.findall(pattern1, html_data.text)
        while True:
            try:
                data = requests.get('http://tn1.72djapp.cn:8399/' + mp3_url[0], heaers).content
                break
            except Exception  as e:
                print("异常：", e)
                time.sleep(10)

        print("开始下载：", mp3_name)
        print("请求：", 'http://tn1.72djapp.cn:8399/' + mp3_url[0])
        with open("mp3\\" + mp3_name, "wb") as f:
            f.write(data)
            print(f"下载 {mp3_name} 完成")

# 这里开始
i = 21
while i <= 1000:
    if i == 0:
        download_mp3("http://www.36dj.com/xc/")
    elif i == 1:
        continue
    else:
        print(f"开始下载第{i}页")
        link = f'http://www.36dj.com/xc/index_{i}.html'
        download_mp3(link)
    i = i + 1
